﻿using Microsoft.Extensions.Logging;
using Zhp.Common.Extention;
using Zhp.Entity.Sys;
using Zhp.IService.Message.Email;
using Zhp.IService.Message.Email.VariableClass;
using Zhp.Service.Base;
using Zhp.SqlSugar.Repository;
using Zhp.Workflow.Entity;
using Zhp.Workflow.Models;

namespace Zhp.Service.Workflow.Notify
{
    public class WorkflowNotifyService : BaseService<WorkflowNotify>, IApproveNotifyService
    {
        private readonly IEmailSender _emailSender;
        private readonly IBaseRepository<SysUser> _sysUserSvc;
        private readonly ILogger<WorkflowNotifyService> _logger;
        public WorkflowNotifyService(IBaseRepository<WorkflowNotify> rep, IEmailSender emailSender, IBaseRepository<SysUser> sysUserSvc, ILogger<WorkflowNotifyService> logger) 
        { 
            _rep = rep;
            _emailSender = emailSender;
            _sysUserSvc = sysUserSvc;
            _logger = logger;
        }

        public async Task SendNotify()
        {
            var list = await _rep.GetListAsync(x => !x.IsSend);
            var userIdList = list.Select(x => x.SubmitterId).Distinct().ToList();
            var userList = await _sysUserSvc.AsQueryable().Where(x => userIdList.Contains(x.Id)).ToListAsync();
            var userDict = userList.ToDictionary(x => x.Id, x => x);
            foreach (var item in list)
            {
                try
                {
                    if (userDict.TryGetValue(item.SubmitterId, out SysUser user))
                    {
                        var variable = new WorkflowNotifyVariable
                        {
                            UserName = user.UserName,
                            NickName = user.NickName,
                            FlowName = item.WorkflowName,
                            ApproveStatusText = item.ApproveStatus.GetDescription(),
                            ApproveRemark = item.ApproveRemark,
                        };
                        string tplName = string.Empty;
                        if (item.ApproveStatus == ApproveStatusEnum.Approved)
                        {
                            tplName = EmailTemplateNameEnum.审批完成通过邮件通知模板.ToString();
                        }
                        else if (item.ApproveStatus == ApproveStatusEnum.Rejected)
                        {
                            tplName = EmailTemplateNameEnum.审批完成拒绝邮件通知模板.ToString();
                        }
                        var result = await _emailSender.SendEmailAsync(tplName, variable, user.Email, user.NickName);
                        if (result)
                        {
                            item.IsSend = true;
                            item.SendTime = DateTime.Now;
                            await _rep.UpdateAsync(item);
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, ex.Message);
                }
            }
        }
    }
}
